package xyz.zhno.project.commons.sentinel.exception;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import xyz.zhno.project.commons.core.dto.ResultError;
import xyz.zhno.project.commons.core.exception.ProjectExceptionCodeEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 404 一级其他框架内部异常处理
 * @author zh_o
 * @date 2020-11-01
 */
@Slf4j
@RestControllerAdvice
public class GlobalUrlNotFoundExceptionHandler implements ErrorController {

    private ErrorAttributes errorAttributes;

    @Override
    @SuppressWarnings("all")
    public String getErrorPath() {
        return "/error";
    }


    /**
     * 异常处理
     * @param request 请求对象
     * @return 响应异常信息
     */
    @RequestMapping("/error")
    public ResponseEntity<ResultError> exceptionHandler(HttpServletRequest request) {
        ServletWebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> attributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
        String attrName = "status";
        Integer status = 404;
        if (attributes.get(attrName).equals(status)) {
            // 404
            ResultError res = ResultError.builder()
                    .code(ProjectExceptionCodeEnum.SYS_RESOURCE_NOT_FOUND.getCode())
                    .message("找不到资源: " + attributes.get("path").toString())
                    .build();
            log.error("Code: {}, Time: {}, Message: {}", "404", DateUtil.now(), "找不到资源:" + attributes.get("path").toString());
            return new ResponseEntity<>(res, HttpStatus.NOT_FOUND);
        }
        // 其他异常
        ResultError res = ResultError.builder()
                .code(ProjectExceptionCodeEnum.SYS_ERROR.getCode())
                .message(attributes.get("message").toString())
                .build();
        log.error("Code: {}, Time: {}, Message: {}", "404", DateUtil.now(), attributes.get("message").toString());
        return new ResponseEntity<>(res, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
